package com.eduprocess.util;

import java.security.*;

import org.apache.commons.codec.binary.Base64;

public class DESTool {

	public static String encrypt(String key, String encryptStr) {
		byte src_byte[] = encryptStr.getBytes();

		try {
			javax.crypto.SecretKey deskey = desKey(key.getBytes("utf-8"));
			byte[] encrypt = desEncrypt(deskey, src_byte);

			return Base64.encodeBase64String(encrypt);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String decrypte(String key, String decryptStr) {
		try {
			javax.crypto.SecretKey deskey = desKey(key.getBytes("utf-8"));
			byte[] decrypt = desDecrypt(deskey, Base64.decodeBase64(decryptStr));
			return new String(decrypt);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static javax.crypto.SecretKey desKey(byte[] key_byte) throws Exception {
		Security.addProvider(new com.sun.crypto.provider.SunJCE());
		javax.crypto.spec.DESedeKeySpec deskeyspec = new javax.crypto.spec.DESedeKeySpec(key_byte);

		javax.crypto.SecretKeyFactory skf = javax.crypto.SecretKeyFactory.getInstance("DESede", "SunJCE");
		return (javax.crypto.SecretKey) skf.generateSecret(deskeyspec);
	}

	public static byte[] desDecrypt(javax.crypto.SecretKey key, byte[] crypt) throws Exception {
		javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DESede/ECB/PKCS5Padding", "SunJCE");
		cipher.init(javax.crypto.Cipher.DECRYPT_MODE, key);
		return cipher.doFinal(crypt);
	}

	public static byte[] desEncrypt(javax.crypto.SecretKey key, byte[] src) throws Exception {
		javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DESede/ECB/PKCS5Padding", "SunJCE");
		cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, key);
		return cipher.doFinal(src);
	}

}